package com.loto.insurance.mis.web.service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import com.loto.insurance.mis.web.db.mapper.CustExtInfoMapper;
import com.loto.insurance.mis.web.db.mapper.CustFeeFlowMapper;
import com.loto.insurance.mis.web.db.mapper.CustInfoMapper;
import com.loto.insurance.mis.web.db.mapper.CustLevelMapper;
import com.loto.insurance.mis.web.entity.CustExtInfo;
import com.loto.insurance.mis.web.entity.CustFeeFlow;
import com.loto.insurance.mis.web.entity.CustInfo;
import com.loto.insurance.mis.web.entity.OemInfo;
import com.loto.insurance.mis.web.entity.ajax.BaseJson;
import com.loto.insurance.mis.web.enumeration.ControllerPropertyEnum;
import com.loto.insurance.mis.web.entity.CustLevel;
import com.loto.utils.Http;
import com.loto.utils.XML;

@Service
public class CustInfoService {
  static Logger logger = LogManager.getLogger(CustInfoService.class);
  @Autowired
  CustInfoMapper custInfoMapper;

  @Autowired
  CustFeeFlowMapper custFeeFlowMapper;

  @Autowired
  CustExtInfoMapper custExtInfoMapper;

  @Autowired
  CustLevelMapper custLevelMapper;

  @Autowired
  DataSourceTransactionManager transactionManager;

  @Autowired
  private DefaultTransactionDefinition def;

  public CustInfo findByName(String name) {
	return custInfoMapper.findByName(name);
  }

  public BigDecimal getOemAdminFee(OemInfo oemInfo) {
	BigDecimal usefulfee = new BigDecimal(0);
	// TODO 从OEM获取
	Map<String, String> paramMap = new HashMap<String, String>();

	paramMap.put("acc", oemInfo.getOemAcc());
	paramMap.put("pin", oemInfo.getOemPin());
	try {
	  String xmlResponse = Http.doPost("http://" + oemInfo.getOemDomain()
		  + "/webservice/queryadminusefulfee.service", paramMap);
	  logger.info(xmlResponse);
	  BaseJson response = XML.fromXML(xmlResponse, BaseJson.class);
	  if (response == null || !response.isOk()) {
		logger.error("获取OEM admin余额[" + oemInfo.getOemId() + "-"
		    + oemInfo.getOemName() + "]失败");
	  } else {
		usefulfee = new BigDecimal(response.getMsg());
		logger.info("获取OEM admin余额[" + oemInfo.getOemId() + "-"
		    + oemInfo.getOemName() + "]成功：" + response.getMsg());
	  }
	} catch (Exception ex) {
	  ex.printStackTrace();
	  logger.error("获取OEM admin余额[" + oemInfo.getOemId() + "-"
		  + oemInfo.getOemName() + "]失败");
	}
	return usefulfee;
  }

  // 调整余额
  public boolean adjustFee(CustFeeFlow feeFlow) {
	TransactionStatus status = transactionManager.getTransaction(def);
	try {
	  long flowId = custFeeFlowMapper.insertCustFeeFlow(feeFlow);
	  // 修改余额
	  Map<String, Object> params = new HashMap<String, Object>();
	  params.put("custId", feeFlow.getFlowCustFid());
	  params.put("changedFee", feeFlow.getFlowChangedFee());
	  int re = custInfoMapper.updateUsefulfeeById(params);

	  transactionManager.commit(status);
	  return flowId > 0 && re > 0;

	} catch (Exception ex) {
	  ex.printStackTrace();
	  transactionManager.rollback(status);
	  return false;
	}
  }

  public List<CustInfo> findAllCust(Map<String, Object> params) {
	return custInfoMapper.findAllCustPager(params);
  }

  public long findAllCustCount(Map<String, Object> params) {
	return custInfoMapper.findAllCustPagerCount(params);
  }

  public CustInfo findById(long custId) {
	return custInfoMapper.findById(custId);
  }

  public CustExtInfo findExtById(long custId) {
	return custExtInfoMapper.findById(custId);
  }

  public BaseJson addCustInfo(CustInfo custInfo, CustExtInfo custExtInfo) {
	BaseJson base = new BaseJson();
	base.setOk(false);

	if (!isCustExisted(custInfo.getCustName())) {

	  TransactionStatus status = transactionManager.getTransaction(def);
	  try {
		custInfoMapper.insertCust(custInfo);
		long custId = custInfo.getCustId();
		custExtInfo.setExtCustFid(custId);
		custExtInfoMapper.insertCustExt(custExtInfo);
		transactionManager.commit(status);
		base.setOk(true);
	  } catch (Exception e) {
		e.printStackTrace();
		transactionManager.rollback(status);
		base.setOk(false);
		base.setMsg(ControllerPropertyEnum.DATA_WRONG.getName());
	  }
	} else {
	  base.setOk(false);
	  base.setMsg(ControllerPropertyEnum.CUST_EXISTED.getName());
	}
	return base;
  }

  public BaseJson updateCustInfo(CustInfo custInfo, CustExtInfo custExtInfo) {
	BaseJson base = new BaseJson();
	base.setOk(false);
	TransactionStatus status = transactionManager.getTransaction(def);
	try {
	  int aa = custInfoMapper.updateCustById(custInfo);
	  int bb = custExtInfoMapper.updateCustExtById(custExtInfo);
	  transactionManager.commit(status);
	  base.setOk(true);
	} catch (Exception e) {
	  e.printStackTrace();
	  transactionManager.rollback(status);
	  base.setOk(false);
	  base.setMsg(ControllerPropertyEnum.DATA_WRONG.getName());
	}
	return base;
  }

  public boolean isCustExisted(String custName) {
	if (custInfoMapper.findByName(custName) != null)
	  return true;
	else
	  return false;
  }

  public List<CustLevel> findAllLevel() {
	return custLevelMapper.findAllLevel();
  }
}
